﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using MySql.Data;
using MySql.Data.MySqlClient;
using Oracle.ManagedDataAccess.Client;
using System.Reflection;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Drawing;
using System.IO;
using OfficeOpenXml.FormulaParsing.Excel.Functions.Math;
using System.Security.Principal;
using System.Security.Cryptography;
using System.Text;
using Meiam.System.Model.Dto;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Threading.Tasks;


namespace Meiam.System.Interfaces
{
    public class MethodHelp
    {
        public static string strmsg = "";


        /// <summary>
        /// 查询配置表获取配置SQL
        /// </summary>
        public static string BaseQuery(string pzid, string con)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append(@"select pzid,source_sys,factory_code,server_ip,source_type,temp_info,operate_type from tms_sql_temp where 1=1 and  pzid='" + pzid + "'");
            DataTable dt_sql = DB.Query(strSql.ToString(), con);
            if (dt_sql.Rows.Count > 0)
            {
                string temp_sql = dt_sql.Rows[0]["temp_info"].ToString();

                return temp_sql;
            }
            else
            {
                return "";
            }
        }

        /// <summary>
        /// 通用配置查询方法
        /// </summary>
        public static DataTable GetTableInfo(string pzid, Dictionary<string, string> dic, string con)
        {
            string strerr = "";
            DataTable dt = null;
            StringBuilder strSql = new StringBuilder();
            string strSQL = BaseQuery(pzid, con);
            if (strSQL != "" && dic.Count > 0)
            {
                //循环dic替换参数值
                foreach (var item in dic)
                {
                    string keyname = item.Key;
                    string value = item.Value;

                    strSQL = strSQL.Replace("{" + keyname + "}", value);

                }
                if (strSQL.Contains("{"))
                {
                    strerr = "替换参数未完成";
                }
                else
                {
                    strSql = new StringBuilder();
                    strSql.Append(strSQL);
                    dt = DB.Query(strSql.ToString(), con);
                }
            }
            else
            {
                strerr = "获取配置信息异常，请检查";
            }

            if (strerr == "")
            {
                return dt;
            }
            else
            {
                return null;
            }

        }

        /// <summary>
        /// 外部数据源查询
        /// </summary>
        public static DataTable GetOutsideTableInfo(string pzid, Dictionary<string, string> dic, string Ocon, string Icon)
        {
            string strerr = "";
            DataTable dt = null;
            StringBuilder strSql = new StringBuilder();
            string strSQL = BaseQuery(pzid, Icon);
            if (strSQL != "" && dic.Count > 0)
            {
                //循环dic替换参数值
                foreach (var item in dic)
                {
                    string keyname = item.Key;
                    string value = item.Value;

                    strSQL = strSQL.Replace("{" + keyname + "}", value);

                }
                if (strSQL.Contains("{"))
                {
                    strerr = "替换参数未完成";
                }
                else
                {
                    strSql = new StringBuilder();
                    strSql.Append(strSQL);
                    dt = DB.Query(strSql.ToString(), Ocon);
                }
            }
            else
            {
                strerr = "获取配置信息异常，请检查";
            }

            if (strerr == "")
            {
                return dt;
            }
            else
            {
                return null;
            }

        }
        /// <summary>
        /// 外部数据源查询
        /// </summary>
        public static DataTable GetOutsideTableInfo_oracle(string pzid, Dictionary<string, string> dic, string Ocon, string Icon)
        {
            string strerr = "";
            DataTable dt = null;
            StringBuilder strSql = new StringBuilder();
            string strSQL = BaseQuery(pzid, Icon);
            if (strSQL != "" && dic.Count > 0)
            {
                //循环dic替换参数值
                foreach (var item in dic)
                {
                    string keyname = item.Key;
                    string value = item.Value;

                    strSQL = strSQL.Replace("{" + keyname + "}", value);

                }
                if (strSQL.Contains("{"))
                {
                    strerr = "替换参数未完成";
                }
                else
                {
                    strSql = new StringBuilder();
                    strSql.Append(strSQL);
                    dt = DB.OracleQuery(strSql.ToString(), Ocon);
                }
            }
            else
            {
                strerr = "获取配置信息异常，请检查";
            }

            if (strerr == "")
            {
                return dt;
            }
            else
            {
                return null;
            }

        }



        public static string InsertOutsideIntoTable(string pzid, Dictionary<string, string> dic, string Ocon, string Icon)
        {
            string strerr = "";
            StringBuilder strSql = new StringBuilder();
            List<string> strSqlList = new List<string>();
            string strSQL = BaseQuery(pzid, Icon);
            if (strSQL != "" && dic.Count > 0)
            {
                //循环dic替换参数值
                foreach (var item in dic)
                {
                    string keyname = item.Key;
                    string value = item.Value;
                    strSQL = strSQL.Replace("{" + keyname + "}", value);

                }
                if (strSQL.Contains("{"))
                {
                    strerr = "替换参数未完成";
                }
                else
                {
                    strSql = new StringBuilder();
                    strSqlList.Add(strSQL.ToString());
                }
                if (strSqlList.Count > 0)
                {
                    bool A = DB.ExecuteNoQueryTran(strSqlList, Ocon);
                    if (A)
                    {

                    }
                    else
                    {
                        strerr = "更新数据库失败，请联系管理员";
                    }

                }
            }
            else
            {
                strerr = "获取配置信息异常，请检查";
            }

            if (strerr == "")
            {
                return "";
            }
            else
            {
                return strerr;
            }

        }

        public static string InsertIntoTable(string pzid, Dictionary<string, string> dic, string con)
        {
            string strerr = "";
            StringBuilder strSql = new StringBuilder();
            List<string> strSqlList = new List<string>();
            string strSQL = BaseQuery(pzid, con);
            if (strSQL != "" && dic.Count > 0)
            {
                //循环dic替换参数值
                foreach (var item in dic)
                {
                    string keyname = item.Key;
                    string value = item.Value;
                    strSQL = strSQL.Replace("{" + keyname + "}", value);

                }
                if (strSQL.Contains("{"))
                {
                    strerr = "替换参数未完成";
                }
                else
                {
                    strSql = new StringBuilder();
                    strSqlList.Add(strSQL.ToString());
                }
                if (strSqlList.Count > 0)
                {
                    bool A = DB.ExecuteNoQueryTran(strSqlList, con);
                    if (A)
                    {

                    }
                    else
                    {
                        strerr = "更新数据库失败，请联系管理员";
                    }

                }
            }
            else
            {
                strerr = "获取配置信息异常，请检查";
            }

            if (strerr == "")
            {
                return "";
            }
            else
            {
                return strerr;
            }

        }

        public static string GetTranSQL(string pzid, Dictionary<string, string> dic, string con)
        {
            string Sql = "";
            StringBuilder strSql = new StringBuilder();
            List<string> strSqlList = new List<string>();
            string strSQL = BaseQuery(pzid, con);
            if (strSQL != "" && dic.Count > 0)
            {
                //循环dic替换参数值
                foreach (var item in dic)
                {
                    string keyname = item.Key;
                    string value = item.Value;
                    strSQL = strSQL.Replace("{" + keyname + "}", value);

                }
                if (strSQL.Contains("{"))
                {
                    Sql = " ";
                }
                else
                {
                    Sql= strSQL;
                }
                
            }
            else
            {
                Sql = "";
            }
            return Sql;            
        }

      
        public static string ChangeCommas(string strchar)
        {
            string re = "";
            if (strchar.Contains(","))
            {
                string[] strArray = strchar.Split(',');
                foreach (var item in strArray)
                {
                    re = re + "'" + item + "',";
                }
                re = re.TrimEnd(',');
            }
            else
            {
                re = "'" + strchar + "'";
            }

            return re;
        }

        //日期转换成时间戳
        public static long GetTimestampByDate(DateTime _date)//根据传入日期生成时间戳
        {
            TimeSpan ts = _date.ToUniversalTime() - new DateTime(1970, 1, 1);
            return (long)ts.TotalMilliseconds;
        }

        /// <summary>
        /// 13位时间戳转 日期格式   1652338858000 -> 2022-05-12 03:00:58
        /// </summary>
        /// <param name="timestamp"></param>
        /// <returns></returns>
        public static DateTime GetDateTimeMilliseconds(long timestamp)//时间戳转日期
        {
            long begtime = timestamp * 10000;
            DateTime dt_1970 = new DateTime(1970, 1, 1, 8, 0, 0);
            long tricks_1970 = dt_1970.Ticks;//1970年1月1日刻度
            long time_tricks = tricks_1970 + begtime;//日志日期刻度
            DateTime dt = new DateTime(time_tricks);//转化为DateTime
            return dt;
        }

        /// <summary>
        /// 创建MD5密码
        /// </summary>
        public static string GetMD5(string input)
        {
            using (MD5 md5 = MD5.Create())
            {
                byte[] inputBytes = Encoding.UTF8.GetBytes(input);
                byte[] hashBytes = md5.ComputeHash(inputBytes);

                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < hashBytes.Length; i++)
                {
                    // 将每个字节转换为两位的十六进制字符串
                    sb.Append(hashBytes[i].ToString("x2"));
                }
                return sb.ToString();
            }
        }


        /// <summary>
        ///内部业务方法：OA消息推送。
        /// </summary>
        public static string WB_OaMessagePush(Dictionary<string, string> dic, string con)
        {
            string strMsg = "";
            StringBuilder strSql = new StringBuilder();

            try
            {
                Dictionary<string, string> urldic = new Dictionary<string, string>(); //查询公用dic
                urldic.Add("function_description", "OA消息推送");//查看URL配置表地址描述
                DataTable url_dt = MethodHelp.GetTableInfo("TMS0004", urldic, con);//获取URL地址
                if (url_dt.Rows.Count > 0)
                {
                    if (dic.Count > 0)
                    {
                        //调用二级缓存到三级接口
                        TMS_OaMessagePushInfo_OARequestDto request_agv = new TMS_OaMessagePushInfo_OARequestDto();
                        request_agv.code = dic["code"].ToString();
                        request_agv.context = dic["context"].ToString();
                        request_agv.creater = dic["creater"].ToString();
                        request_agv.linkMobileUrl = dic["linkMobileUrl"].ToString();
                        request_agv.linkUrl = dic["linkUrl"].ToString();
                        request_agv.title = dic["title"].ToString();
                        request_agv.workCodeList = dic["workCodeList"].ToString();
                        string jsonText = JsonConvert.SerializeObject(request_agv);
                        var reAgv = DB.httpPost(url_dt.Rows[0]["interface_url"].ToString(), jsonText, "", "否");
                        TMS_OaMessagePushInfo_OAResponseDto psp = JsonConvert.DeserializeObject<TMS_OaMessagePushInfo_OAResponseDto>(reAgv);

                    }
                }
                else
                {
                    strMsg = "URL: <OA消息推送> not find";
                }
            }
            catch (Exception ex)
            {
                strMsg = ex.ToString();
            }

            if (strMsg == "")
            {
                return "";
            }
            else
            {
                return strMsg;
            }

        }



        /// <summary>
        ///内部业务方法：日志写入。
        /// </summary>
        public static string log_create(Dictionary<string, string> dic, string con)
        {
            string strMsg = "";
            StringBuilder strSql = new StringBuilder();

            try
            {
                Dictionary<string, string> urldic = new Dictionary<string, string>(); //查询公用dic
                urldic.Add("function_description", "日志写入");//查看URL配置表地址描述
                DataTable url_dt = MethodHelp.GetTableInfo("TMS0004", urldic, con);//获取URL地址
                if (url_dt.Rows.Count > 0)
                {
                    if (dic.Count > 0)
                    {
                        //调用二级缓存到三级接口
                        SysLogRecordRequestDto request_agv = new SysLogRecordRequestDto();
                        request_agv.Url = dic["Url"].ToString();
                        request_agv.request = dic["request"].ToString();
                        request_agv.result = dic["result"].ToString();
                        request_agv.request_time = dic["request_time"].ToString();
                        string jsonText = JsonConvert.SerializeObject(request_agv);
                        var reAgv = DB.httpPost(url_dt.Rows[0]["interface_url"].ToString(), jsonText, "", "否");
                        SysLogRecordResponseDto psp = JsonConvert.DeserializeObject<SysLogRecordResponseDto>(reAgv);

                    }
                }
                else
                {
                    strMsg = "URL: <日志写入> not find";
                }
            }
            catch (Exception ex)
            {
                strMsg = ex.ToString();
            }

            if (strMsg == "")
            {
                return "";
            }
            else
            {
                return strMsg;
            }

        }

    }

}